from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.enum.text import PP_ALIGN
from typing import List, Dict, Any
import openai
import os
from loguru import logger

class PPTGenerator:
    def __init__(self, api_key: str):
        """Initialize the PPT generator with DeepSeek API key."""
        openai.api_key = api_key
        openai.api_base = "https://api.deepseek.com/v1"

    def generate_content(self, topic: str) -> Dict[str, Any]:
        """Generate PPT content structure using DeepSeek."""
        try:
            # Create a system message for PPT generation
            system_message = """You are a professional presentation creator. 
            Create a detailed presentation outline for the given topic. 
            The response should be in JSON format with the following structure:
            {
                "title": "Presentation Title",
                "slides": [
                    {
                        "title": "Slide Title",
                        "content": ["Point 1", "Point 2", "Point 3"],
                        "notes": "Speaker notes for this slide"
                    }
                ]
            }"""

            # Call DeepSeek API
            response = openai.ChatCompletion.create(
                model="deepseek-chat",
                messages=[
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": f"Create a presentation about: {topic}"}
                ],
                temperature=0.7,
                max_tokens=2000
            )

            # Parse the response
            content = response.choices[0].message.content
            return eval(content)  # Convert string to dict
        except Exception as e:
            logger.error(f"Error generating content: {str(e)}")
            raise

    def create_presentation(self, content: Dict[str, Any], output_path: str) -> str:
        """Create a PowerPoint presentation from the generated content."""
        try:
            prs = Presentation()

            # Create title slide
            title_slide_layout = prs.slide_layouts[0]
            slide = prs.slides.add_slide(title_slide_layout)
            title = slide.shapes.title
            title.text = content["title"]

            # Create content slides
            for slide_content in content["slides"]:
                content_slide_layout = prs.slide_layouts[1]
                slide = prs.slides.add_slide(content_slide_layout)
                
                # Set slide title
                title = slide.shapes.title
                title.text = slide_content["title"]

                # Add content
                body = slide.shapes.placeholders[1]
                tf = body.text_frame
                
                for point in slide_content["content"]:
                    p = tf.add_paragraph()
                    p.text = point
                    p.level = 0

                # Add speaker notes if present
                if "notes" in slide_content:
                    notes_slide = slide.notes_slide
                    notes_slide.notes_text_frame.text = slide_content["notes"]

            # Save the presentation
            prs.save(output_path)
            return output_path

        except Exception as e:
            logger.error(f"Error creating presentation: {str(e)}")
            raise

    def generate_ppt(self, topic: str, output_path: str) -> str:
        """Generate a complete PPT from topic to final file."""
        content = self.generate_content(topic)
        return self.create_presentation(content, output_path) 